package com.lancoo.answer.ui.ques.quesBody;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lancoo.answer.R;
import com.lancoo.answer.component.InteractWebView;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.ui.paper.PaperFragment;
import com.lancoo.answer.ui.ques.SpliteLayoutFragment;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.rxjava.rxlife.RxLife;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by pengmi on 2021/12/16 9:30
 * Description:通用题干加载fragment
 */
public class NormalQuseBodyFragment extends Fragment {

    private static final String TAG = "NormalQuseBodyFragment";
    private FrameLayout frameLayout;
    private InteractWebView interactWebView;
    private Ques ques;
    private String currentItemSortIndex = "";
    private int loadChildIndex = -1;

    public static Fragment loadQueseFragment(int kindIndex, int queseIndex, int childIndex, int defaultIndex) {
        NormalQuseBodyFragment queseFragment = new NormalQuseBodyFragment();
        Bundle mBundle = new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, kindIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX, childIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_ques_body, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() == null || getContext() == null || getActivity() == null) {
            return;
        }
        if (ConstantBean.Companion.getConstantExamBean() == null) {
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if (kindBeanListk == null) {
            return;
        }
        int typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        int quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        int childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        if (kindBeanListk.get(typeIndex) == null ||
                kindBeanListk.get(typeIndex).getQuesList() == null) {
            return;
        }

        ques = kindBeanListk.get(typeIndex).getQuesList().get(quesIndex);
        interactWebView = new InteractWebView(getContext());
        if (ques == null || ques.getQuesBody() == null) {
            return;
        }
        frameLayout = view.findViewById(R.id.framelayout);
        frameLayout.addView(interactWebView);
        String quesBody = ques.getQuesBody();//大题题干
        Boolean isIndentation = ques.getIsIndentQuesBody();
        if (TextUtils.isEmpty(quesBody)) {//为空，取小题题干
            if (ques.getChildList() != null && ques.getChildList().size() > 0) {
                if (childIndex < ques.getChildList().size()) {
                    quesBody = ques.getChildList().get(childIndex).getChildAsk();
                    isIndentation = ques.getChildList().get(childIndex).getIsIndentChildAsk();
                } else {
                    quesBody = ques.getChildList().get(0).getChildAsk();
                    isIndentation = ques.getChildList().get(0).getIsIndentChildAsk();
                }
            }
        }
        if (quesBody == null) {
            quesBody = "";
        }
//        SplitViewHeightAdjustTuils.splitViewDefaultLoadHeight(ques, );
        if (ConstantBean.getTaskState() == TaskState.ORIGINAL) {
            interactWebView.showOrHideAnalysisButton(0);
        } else {
            interactWebView.showOrHideAnalysisButton(1);
        }
        interactWebView.setQues(ques);
        interactWebView.setIsIndentation(isIndentation);
        if (loadChildIndex == -1) {
            int anInt = getArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX);
            loadChildIndex = anInt;
        }

        if (quesBody.contains("This part is to")) {
            quesBody = quesBody.replaceFirst(">", "><strong>Directions:</strong>");
        }
        interactWebView.initWebView(getActivity(), quesBody, new InteractWebView.Callback() {
            @Override
            public void clickCallback(@NotNull String position) {
                Log.e(TAG, "clickCallback position:" + position);
                if (ConstantBean.getTaskState() != TaskState.TRAINING) {
                    wvLoadUrl(position);
                    getRealIndex(position);
                }
            }

            @Override
            public void finishCallback() {
                initLayout();
                Log.e("00916", "finishCallback:");
                if (ConstantBean.getTaskState() != TaskState.TRAINING) {
                    wvLoadUrl("");
                    if (getArguments() != null && loadChildIndex >= 0) {
                        loadItemIndex(loadChildIndex, 0);
                    } else {
                        loadItemIndex(0, 0);
                    }
                }
                if (ConstantBean.getTaskState() == TaskState.TRAINING) {
                    Observable.timer(200, TimeUnit.MILLISECONDS)//必须加延时才能算准高度
                            .observeOn(AndroidSchedulers.mainThread())
                            .as(RxLife.as(NormalQuseBodyFragment.this))
                            .subscribe(aLong -> {
                                if (getArguments() == null) {
                                    return;
                                }
                                openPalette();
                            });
                }
//                interactWebView.loadHighKLg("javascript:InitPageData('"+names+"','"+sb_code.toString()+"')");
            }
        });
    }

    private void openPalette() {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE);
        boolean openDash = sharedPreferences.getBoolean(AnswerConstant.SP_OPEN_DASH, true);
        if (openDash) {
            interactWebView.openPalette();
        } else {
            interactWebView.closePalette();
        }
    }

    private void wvLoadUrl(String position) {
        if (TextUtils.equals(currentItemSortIndex, position)) {
            return;
        }
        if (interactWebView == null) {
            return;
        }
        currentItemSortIndex = position;
        Log.e(TAG, "wvLoadUrl:" + position);
        interactWebView.scrollPosition(position);
        for (Child it : ques.getChildList()) {
            if (ConstantBean.getTaskState() == TaskState.ORIGINAL) {
                interactWebView.loadOriginUrl(it.getItemList().get(0),
                        position.equals(it.getItemList().get(0).getItemSortIndex()),
                        true);
            } else {
                interactWebView.loadUrl(it.getItemList().get(0),
                        position.equals(it.getItemList().get(0).getItemSortIndex()),
                        false,
                        true);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (interactWebView != null) {
            interactWebView.release();
        }
        if (frameLayout != null) {
            frameLayout.removeAllViews();
        }
    }

    public void loadItemIndex(int childIndex, int itemIndex) {
        Log.e(TAG, "childIndex:" + childIndex);
        this.loadChildIndex = childIndex;
        if (ConstantBean.getTaskState() != TaskState.TRAINING &&
                ques != null && ques.getChildList() != null && ques.getChildList().size() > 0) {

            String typeNo = ques.getTypeNo();
            if (TextUtils.isEmpty(typeNo)) {
                return;
            }
            if (TextUtils.equals(typeNo, "H") || TextUtils.equals(typeNo, "D")
                    || TextUtils.equals(typeNo, "X") || TextUtils.equals(typeNo, "k")
                    || TextUtils.equals(typeNo, "P")) {
                return;
            }


            List<Child> childList = ques.getChildList();
            if (childIndex < childList.size() && childIndex >= 0) {
                if (childList.get(childIndex).getItemList() != null &&
                        childList.get(childIndex).getItemList().size() > 0) {

                    wvLoadUrl(childList.get(this.loadChildIndex).getItemList().get(0).getItemSortIndex());
                }
            }

        }
    }

    private void getRealIndex(String position) {

        if (ques == null || ques.getChildList() == null) {
            return;
        }
        int childIndex = 0;
        for (Child child : ques.getChildList()) {
            List<Item> itemList = child.getItemList();
            if (itemList == null) {
                continue;
            }
            if (TextUtils.equals(position, itemList.get(0).getItemSortIndex())) {
                break;
            }
            childIndex++;
        }
        Log.e(TAG, "getRealIndex" + childIndex);
        FragmentCommunicationUtils.dealWithQuesBodyInteraction(this, childIndex);
    }


    public void adjustFontSize() {
        if (interactWebView != null) {
            interactWebView.setFontSize();
        }
    }

    public void initLayout() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof SpliteLayoutFragment) {
            ((SpliteLayoutFragment) parentFragment).initLayout();
        }
    }
}